﻿using QuickChat_Service.Repositories.Database;
using QuickChat_Service.Repositories.Repositories.Interfaces;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace QuickChat_Service.Repositories.Repositories.Implementations
{
    public class EFMessageRepository : EFRepository<Message>, IMessageRepository
    {
        public EFMessageRepository(QuickChatApplicationEntities context) : base(context) { }

        #region Interface Implementation

        public void SendMessage(string message, int sendersId, int sessionId)
        {
            //If I get errors, I should manually set the talker attribute, adn others
            Message newMessage = new Message {
                MessageText = message,
                SendersId = sendersId,
                SentTime = DateTime.UtcNow,
                SessionId = sessionId
            };

            DbContext.Set<ChatSession>().Find(sessionId).Messages.Add(newMessage);
        }

        public IQueryable<Message> GetMessagesInSession(int sessionId)
        {
            ChatSession session = DbContext.Set<ChatSession>().Include("Talkers").
                Include("Messages").SingleOrDefault(sess => sess.SessionId == sessionId);
            
            if(session == null)
            {
                throw new NotImplementedException("Session No longer exists or cannot retrieve inactive session");
            }

            return session.Messages.AsQueryable();
        }

        #endregion
    }
}